<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="04存储过程和函数+游标+存储引擎+mysql体系+读写锁+行锁表锁+间隙锁, luckyzmj 计算机 网络安全 渗透测试">
    <meta name="description" content="无">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google-site-verification" content="pBWoGvVEP36FzzS4xIpoMejc5UKi3RKcxd9rWWcjiDg" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>04存储过程和函数+游标+存储引擎+mysql体系+读写锁+行锁表锁+间隙锁 | Long</title>

    <link rel="icon" type="image/jpeg" href="https://s1.ax1x.com/2020/05/17/YR20js.jpg">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;900&display=swap" rel="stylesheet" media="print" onload="this.media='all'">
    <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?aaa6c944b0ed07922901d7fc571a171d";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
<meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="Long" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="https://s1.ax1x.com/2020/05/17/YRWsYT.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Long</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/census">
          
          <i class="fas fa-layer-group" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>统计</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-paper-plane" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>时轴</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tag" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>标签</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-heartbeat" style="zoom: 0.6;"></i>
      
      <span>清单</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/List/music">
          
          <i class="fas fa-music" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>音乐</span>
        </a>
      </li>
      
      <li>
        <a href="/List/galleries">
          
          <i class="fas fa-image" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>相册</span>
        </a>
      </li>
      
      <li>
        <a href="/List/movies">
          
          <i class="fas fa-film" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>视频</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-envelope" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tools" class="waves-effect waves-light">
      
      <i class="fas fa-suitcase" style="zoom: 0.6;"></i>
      
      <span>百宝箱</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/Windows" class="waves-effect waves-light">
      
      <i class="fas fa-desktop" style="zoom: 0.6;"></i>
      
      <span>Windows</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-link" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="https://s1.ax1x.com/2020/05/17/YRWsYT.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Long</div>
        <div class="logo-desc">
            
            无
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-archive"></i>
			
			归档
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/census " style="margin-left:75px">
				  
				   <i class="fa fas fa-layer-group" style="position: absolute;left:50px" ></i>
			      
		          <span>统计</span>
                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-paper-plane" style="position: absolute;left:50px" ></i>
			      
		          <span>时轴</span>
                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tag" style="position: absolute;left:50px" ></i>
			      
		          <span>标签</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-heartbeat"></i>
			
			清单
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/List/music " style="margin-left:75px">
				  
				   <i class="fa fas fa-music" style="position: absolute;left:50px" ></i>
			      
		          <span>音乐</span>
                  </a>
                </li>
              
                <li>

                  <a href="/List/galleries " style="margin-left:75px">
				  
				   <i class="fa fas fa-image" style="position: absolute;left:50px" ></i>
			      
		          <span>相册</span>
                  </a>
                </li>
              
                <li>

                  <a href="/List/movies " style="margin-left:75px">
				  
				   <i class="fa fas fa-film" style="position: absolute;left:50px" ></i>
			      
		          <span>视频</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-envelope"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tools" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-suitcase"></i>
			
			百宝箱
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/Windows" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-desktop"></i>
			
			Windows
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-link"></i>
			
			友链
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/LuckyZmj/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/LuckyZmj/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/banner/10.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">04存储过程和函数+游标+存储引擎+mysql体系+读写锁+行锁表锁+间隙锁</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        background-color: white;
        width: 345px;
        padding-left: 20px;
        border-radius: 10px;
        box-shadow: 0 10px 35px 2px rgba(0, 0, 0, .15), 0 5px 15px rgba(0, 0, 0, .07), 0 2px 5px -5px rgba(0, 0, 0, .1) !important;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }
    
    #toc-content {
        height: calc(100vh - 300px);
        overflow: scroll;

    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
        bottom: 120px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">
                                <span class="chip bg-color">数据库</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-category">
                                数据库
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-15
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-09-17
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7.5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    28 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id=""><a href="#" class="headerlink" title=""></a></h2><h2 id="1、存储过程"><a href="#1、存储过程" class="headerlink" title="1、存储过程"></a>1、存储过程</h2><blockquote>
<p><strong>【概念】</strong>：mysql中的存储过程和函数是 <strong>一组预先编译并存储在数据库中的SQL 语句的集合</strong>，我们可以通过调用存储过程和函数来执行一组SQL语句的集合。</p>
</blockquote>
<h3 id="1、创建存储过程"><a href="#1、创建存储过程" class="headerlink" title="1、创建存储过程"></a>1、创建存储过程</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment"># 查询过程赋值</span>
<span class="token keyword">delimiter</span> $
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test3<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
	<span class="token comment"># 声明变量num</span>
	<span class="token keyword">declare</span> num <span class="token keyword">int</span><span class="token punctuation">;</span>
	<span class="token comment"># 查询城市表行记录数并赋值num</span>
	<span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token operator">*</span><span class="token punctuation">)</span> <span class="token keyword">into</span> num <span class="token keyword">from</span> city<span class="token punctuation">;</span>
	<span class="token comment"># 查询</span>
	<span class="token keyword">select</span> num<span class="token punctuation">;</span>
<span class="token keyword">end</span>$

<span class="token comment"># 调用</span>
<span class="token keyword">call</span> pro_test3<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>【说明】</p>
<p>​    1.参数列表包含三部分：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">		参数模式    参数名        参数类型
举例：   <span class="token operator">IN</span>		 stuname      <span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>​        参数模式：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token operator">IN</span>:该参数可以作为输入，也就是该参数需要调用者传入值
<span class="token keyword">OUT</span>:该参数可以作为输出，也就是该参数可以作为返回值
<span class="token keyword">INOUT</span>:该参数既可以作为输入又可以作为输出，也就是该参数既需要传入值，又可以返回值<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>​    如果存储过程体仅仅只有一句话，begin  end可以省略。</p>
<h3 id="2、查看存储过程"><a href="#2、查看存储过程" class="headerlink" title="2、查看存储过程"></a>2、查看存储过程</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">--  查询指定数据库中的所有的存储过程</span>
<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> mysql<span class="token punctuation">.</span><span class="token keyword">proc</span> <span class="token keyword">where</span> db<span class="token operator">=</span><span class="token string">'数据库名'</span> \G<span class="token punctuation">;</span>
举例：
<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> mysql<span class="token punctuation">.</span><span class="token keyword">proc</span> <span class="token keyword">where</span> db<span class="token operator">=</span><span class="token string">'day0401'</span> \G<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 查看创建某个存储过程的语句信息</span>
<span class="token keyword">show</span> <span class="token keyword">create</span> <span class="token keyword">procedure</span> 存储过程名<span class="token punctuation">;</span>
<span class="token comment">-- 举例：</span>
<span class="token keyword">show</span> <span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test1 \G<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="3、删除存储过程"><a href="#3、删除存储过程" class="headerlink" title="3、删除存储过程"></a>3、删除存储过程</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">drop</span> <span class="token keyword">procedure</span> 存储过程名<span class="token punctuation">;</span>
<span class="token comment">-- 举例：</span>
<span class="token keyword">drop</span> <span class="token keyword">procedure</span> pro_test1<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>



<h3 id="4、存储过程语法"><a href="#4、存储过程语法" class="headerlink" title="4、存储过程语法"></a>4、存储过程语法</h3><h4 id="1、变量"><a href="#1、变量" class="headerlink" title="1、变量"></a>1、变量</h4><ul>
<li><p>declare（声明）</p>
<p>​    通过 declare 可以定义一个局部变量，该变量的作用范围只能在 BEGIN…END 块中。</p>
</li>
</ul>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">declare</span> 变量名<span class="token number">1</span><span class="token punctuation">,</span>变量名<span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>  变量的数据类型 <span class="token punctuation">[</span><span class="token keyword">default</span> 默认值<span class="token punctuation">]</span> <span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 1.创建存储过程</span>
  <span class="token keyword">delimiter</span> $
  <span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test2<span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">begin</span>
      <span class="token keyword">declare</span> num <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">5</span><span class="token punctuation">;</span>
      <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'num的值是:'</span><span class="token punctuation">,</span>num<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">end</span> $
  
  <span class="token comment">-- 2.调用存储过程</span>
  <span class="token keyword">call</span> pro_test2<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<ul>
<li><p>SET(赋值)</p>
<p>直接赋值使用 SET，可以赋常量或者赋表达式</p>
</li>
</ul>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SET</span> 变量名<span class="token number">1</span> <span class="token operator">=</span> 表达式<span class="token number">1</span><span class="token punctuation">,</span>变量名<span class="token number">2</span><span class="token operator">=</span>表达式<span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<div style="background-color:#42C0A3;">示例:定义变量num默认值是0，设置num值+10 ，并查询</div>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 1.创建存储过程</span>
  <span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test3<span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">begin</span>
  	<span class="token keyword">declare</span> num <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">0</span><span class="token punctuation">;</span>
  	<span class="token keyword">set</span> num <span class="token operator">=</span> num <span class="token operator">+</span> <span class="token number">10</span><span class="token punctuation">;</span>
  	<span class="token keyword">select</span> num<span class="token punctuation">;</span>
  <span class="token keyword">end</span>$
  <span class="token comment">-- 2.调用存储过程</span>
  <span class="token keyword">call</span> pro_test3<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>也可以通过select … into 方式进行赋值操作 :</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">  <span class="token comment">-- 1.创建存储过程</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test4<span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">begin</span>
  	<span class="token keyword">declare</span> num <span class="token keyword">int</span><span class="token punctuation">;</span>
  	<span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token operator">*</span><span class="token punctuation">)</span> <span class="token keyword">into</span> num <span class="token keyword">from</span> city<span class="token punctuation">;</span>
  	<span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'city表中的记录数为:'</span><span class="token punctuation">,</span>num<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">end</span>$
  <span class="token comment">-- 2.调用存储过程</span>
  <span class="token keyword">call</span> pro_test4<span class="token punctuation">(</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="2、if条件判断"><a href="#2、if条件判断" class="headerlink" title="2、if条件判断"></a>2、if条件判断</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- if条件后面为真执行对应then后面的语句，不满足就执行后面的elseif，如果elseif条件也不满足则继续向下执行判断，如果都不满足条件就执行else后面的语句</span>
<span class="token keyword">if</span> 条件<span class="token number">1</span> <span class="token keyword">then</span> 语句<span class="token number">1</span><span class="token punctuation">;</span>
<span class="token punctuation">[</span><span class="token keyword">elseif</span> 条件<span class="token number">2</span> <span class="token keyword">then</span> 语句<span class="token number">2</span><span class="token punctuation">;</span><span class="token punctuation">]</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">[</span><span class="token keyword">else</span> 语句n<span class="token punctuation">;</span><span class="token punctuation">]</span>
<span class="token keyword">end</span> <span class="token keyword">if</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>注意：1）上述if只能用在begin end中.2）elseif不能分开写，必须在一起，否则报错</strong></p>
<p>需求：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">根据定义的体重变量，判定当前体重的所属的身材类型
    <span class="token number">170</span> 及以上 <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">&gt;</span> 身材肥胖
    <span class="token number">150</span> <span class="token operator">-</span> <span class="token number">170</span> <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-&gt;</span> 标准身材
    <span class="token number">150</span> 以下 <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">&gt;</span> 身材偏瘦<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<div style="background-color:#42C0A3;">示例: </div>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建存储过程</span>
<span class="token keyword">delimiter</span> $
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test5<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
    <span class="token keyword">declare</span> weight <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">175</span><span class="token punctuation">;</span>
    <span class="token keyword">declare</span> description <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">50</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token string">''</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> weight <span class="token operator">&gt;=</span> <span class="token number">170</span> <span class="token keyword">then</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'身材肥胖'</span><span class="token punctuation">;</span>
    <span class="token keyword">elseif</span> weight <span class="token operator">&gt;=</span> <span class="token number">150</span> <span class="token operator">and</span> weight <span class="token operator">&lt;</span> <span class="token number">170</span> <span class="token keyword">then</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'标准身材'</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'身材偏瘦'</span><span class="token punctuation">;</span>
    <span class="token keyword">end</span> <span class="token keyword">if</span><span class="token punctuation">;</span>
    <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'体重:'</span><span class="token punctuation">,</span>weight<span class="token punctuation">,</span><span class="token string">'对应的身材类型为:'</span><span class="token punctuation">,</span>description<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">end</span>$

<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test5<span class="token punctuation">(</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="3、-传递参数"><a href="#3、-传递参数" class="headerlink" title="3、 传递参数"></a>3、 传递参数</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token keyword">procedure</span> procedure_name<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token operator">in</span><span class="token operator">/</span><span class="token keyword">out</span><span class="token operator">/</span><span class="token keyword">inout</span><span class="token punctuation">]</span>  参数名  参数类型<span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>

<span class="token operator">IN</span> :  该参数可以作为输入，也就是需要调用方传入值 <span class="token punctuation">,</span> 默认
<span class="token keyword">OUT</span>:  该参数作为输出，也就是该参数可以作为返回值
<span class="token keyword">INOUT</span>: 既可以作为输入参数，也可以作为输出参数<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="IN-输入"><a href="#IN-输入" class="headerlink" title="IN 输入"></a>IN 输入</h5><p>IN :  该参数可以作为输入，也就是需要调用方传入值 , 默认。</p>
<p>调用格式：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">call</span> 存储过程名<span class="token punctuation">(</span>数据<span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>需求:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">根据传入的体重变量，判定当前体重的所属的身材类型 <span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<div style="background-color:#42C0A3;">示例: </div>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建存储过程，不用声明weight变量了，已经在小括号中定义了</span>
<span class="token keyword">delimiter</span> $
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test6<span class="token punctuation">(</span><span class="token operator">in</span> weight <span class="token keyword">int</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
    <span class="token keyword">declare</span> description <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">50</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token string">''</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> weight <span class="token operator">&gt;=</span> <span class="token number">170</span> <span class="token keyword">then</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'身材肥胖'</span><span class="token punctuation">;</span>
    <span class="token keyword">elseif</span> weight <span class="token operator">&gt;=</span> <span class="token number">150</span> <span class="token operator">and</span> weight <span class="token operator">&lt;</span> <span class="token number">170</span> <span class="token keyword">then</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'标准身材'</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'身材偏瘦'</span><span class="token punctuation">;</span>
    <span class="token keyword">end</span> <span class="token keyword">if</span><span class="token punctuation">;</span>
    <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'体重:'</span><span class="token punctuation">,</span>weight<span class="token punctuation">,</span><span class="token string">'对应的身材类型为:'</span><span class="token punctuation">,</span>description<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">end</span>$
<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test6<span class="token punctuation">(</span><span class="token number">160</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h5 id="OUT-输出"><a href="#OUT-输出" class="headerlink" title="OUT 输出"></a>OUT 输出</h5><p>OUT:  该参数作为输出，也就是该参数可以作为返回值</p>
<div style="background-color:#42C0A3;">示例: </div>

<p>需求:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">根据传入的体重变量，获取当前体重的所属的身材类型<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>【创建存储过程的sql语句】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建存储过程</span>
<span class="token keyword">delimiter</span> $
<span class="token comment">-- 不用声明weight和description变量了，已经在小括号中定义了,description表示返回，我们在调用存储过程的时候需要使用变量接收</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test7<span class="token punctuation">(</span><span class="token operator">in</span> weight <span class="token keyword">int</span><span class="token punctuation">,</span><span class="token keyword">out</span> description <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
    <span class="token keyword">if</span> weight <span class="token operator">&gt;=</span> <span class="token number">170</span> <span class="token keyword">then</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'身材肥胖'</span><span class="token punctuation">;</span>
    <span class="token keyword">elseif</span> weight <span class="token operator">&gt;=</span> <span class="token number">150</span> <span class="token operator">and</span> weight <span class="token operator">&lt;</span> <span class="token number">170</span> <span class="token keyword">then</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'标准身材'</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
      <span class="token keyword">set</span> description <span class="token operator">=</span> <span class="token string">'身材偏瘦'</span><span class="token punctuation">;</span>
    <span class="token keyword">end</span> <span class="token keyword">if</span><span class="token punctuation">;</span>
<span class="token keyword">end</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>说明：由于我们需要在调用存储过程中接收返回的description的值，所以我们不用在存储过程中使用select查看description的值了。</p>
<p>上述我们只是创建了有返回值的存储过程，那么接下来我们需要调用存储过程，调用有返回值的存储过程需要使用变量接收返回值。</p>
<p>那么这里我们可以按照如下方式接收返回值：</p>
<p>【调用存储过程】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test7<span class="token punctuation">(</span><span class="token number">168</span><span class="token punctuation">,</span><span class="token variable">@desc</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><b><font color="red">知识小贴士</font></b><br>@desc : 这种变量要在变量名称前面加上“@”符号，叫做用户会话变量，代表整个会话过程他都是有作用的。@后面属于标识符，随便定义。</p>
<p>作用域：针对当前会话(连接)有效，同于会话变量的作用域。</p>
<p>【查看返回值变量接收的结果】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token variable">@desc$</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>说明：本身存储过程是没有返回值的函数，是一个过程，没有结果。上述所说的返回值其实不是真正返回值，只是我们传递一个变量到存储过程中，在存储过程中修改了该变量值，然后在调用存储过程的位置在获取修改后的变量值。</p>
<p>举例：类似于java中在方法外部定义变量，在方法中修改变量，然后在方法外部获取修改后的变量是一个意思。</p>
<h5 id="INOUT输入输出"><a href="#INOUT输入输出" class="headerlink" title="INOUT输入输出"></a>INOUT输入输出</h5><p>INOUT: 既可以作为输入参数，也可以作为输出参数</p>
<p>需求：创建带inout模式参数的存储过程。</p>
<p>传入a和b两个值，最终将a和b都乘以2并返回。</p>
<p>【创建存储过程】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test8<span class="token punctuation">(</span><span class="token keyword">inout</span> a <span class="token keyword">int</span><span class="token punctuation">,</span><span class="token keyword">inout</span> b <span class="token keyword">int</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
    <span class="token keyword">set</span> a <span class="token operator">=</span> a <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">;</span>
    <span class="token keyword">set</span> b <span class="token operator">=</span> b <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">;</span>
<span class="token keyword">end</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>【调用存储过程】</p>
<p>说明：我们在调用存储过程的时候需要给a和b传入两个数据，首先我们不能直接传递常量，因为我们还要使用select进行对结果的查询。所以这里我们先使用set命令定义两个变量。</p>
<p>自定义用户变量，声明并初始化：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">set</span> @变量名<span class="token operator">=</span>值$
举例：
<span class="token keyword">set</span> <span class="token variable">@m</span><span class="token operator">=</span><span class="token number">10</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>代码：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 定义用户变量并初始化</span>
<span class="token keyword">set</span> <span class="token variable">@m</span><span class="token operator">=</span><span class="token number">10</span>$
<span class="token keyword">set</span> <span class="token variable">@n</span><span class="token operator">=</span><span class="token number">20</span>$
<span class="token comment">-- 调用存储过程并将变量值传递给存储过程中的a和b</span>
<span class="token keyword">call</span> pro_test8<span class="token punctuation">(</span><span class="token variable">@m</span><span class="token punctuation">,</span><span class="token variable">@n</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>【查看存储过程返回的值】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token variable">@m</span><span class="token punctuation">,</span><span class="token variable">@n$</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>



<h4 id="4、case结构"><a href="#4、case结构" class="headerlink" title="4、case结构"></a>4、case结构</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">方式一 :
<span class="token comment">-- 拿case后面的值和when后面的值依次比较，相等就执行then后面的语句，如果都不相等，就执行else后面的语句</span>
<span class="token keyword">CASE</span> 值
    <span class="token keyword">WHEN</span> 值<span class="token number">1</span> <span class="token keyword">THEN</span> 语句<span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">[</span><span class="token keyword">WHEN</span> 值<span class="token number">2</span> <span class="token keyword">THEN</span> 语句<span class="token number">2</span><span class="token punctuation">]</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token punctuation">[</span><span class="token keyword">ELSE</span> 语句<span class="token number">3</span><span class="token punctuation">]</span>
<span class="token keyword">END</span> <span class="token keyword">CASE</span><span class="token punctuation">;</span>

方式二 :
<span class="token comment">-- 说明：WHEN后面的任意一个 条件表达式 是true，就执行then后面的语句，如果都是false，那么执行else后面的语句，多个when只会执行一个</span>
<span class="token keyword">CASE</span>
    <span class="token keyword">WHEN</span> 条件表达式<span class="token number">1</span> <span class="token keyword">THEN</span> 语句<span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">[</span><span class="token keyword">WHEN</span> 条件表达式<span class="token number">2</span> <span class="token keyword">THEN</span> 语句<span class="token number">2</span><span class="token punctuation">;</span><span class="token punctuation">]</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token punctuation">[</span><span class="token keyword">ELSE</span> 语句<span class="token number">3</span><span class="token punctuation">]</span>
<span class="token keyword">END</span> <span class="token keyword">CASE</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>需求:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">给定一个月份 <span class="token punctuation">,</span> 然后计算出所在的季度<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>sql</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建存储过程</span>
<span class="token keyword">delimiter</span> $
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test9<span class="token punctuation">(</span><span class="token operator">in</span> <span class="token keyword">month</span> <span class="token keyword">int</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
    <span class="token keyword">declare</span> result <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">case</span>
     <span class="token keyword">when</span> <span class="token keyword">month</span> <span class="token operator">&gt;=</span> <span class="token number">1</span> <span class="token operator">and</span> <span class="token keyword">month</span> <span class="token operator">&lt;=</span><span class="token number">3</span> <span class="token keyword">then</span>
       <span class="token keyword">set</span> result <span class="token operator">=</span> <span class="token string">'第一季度'</span><span class="token punctuation">;</span>
     <span class="token keyword">when</span> <span class="token keyword">month</span> <span class="token operator">&gt;=</span> <span class="token number">4</span> <span class="token operator">and</span> <span class="token keyword">month</span> <span class="token operator">&lt;=</span><span class="token number">6</span> <span class="token keyword">then</span>
       <span class="token keyword">set</span> result <span class="token operator">=</span> <span class="token string">'第二季度'</span><span class="token punctuation">;</span>
     <span class="token keyword">when</span> <span class="token keyword">month</span> <span class="token operator">&gt;=</span> <span class="token number">7</span> <span class="token operator">and</span> <span class="token keyword">month</span> <span class="token operator">&lt;=</span><span class="token number">9</span> <span class="token keyword">then</span>
       <span class="token keyword">set</span> result <span class="token operator">=</span> <span class="token string">'第三季度'</span><span class="token punctuation">;</span>
     <span class="token keyword">else</span>
       <span class="token keyword">set</span> result <span class="token operator">=</span> <span class="token string">'第四季度'</span><span class="token punctuation">;</span>
    <span class="token keyword">end</span> <span class="token keyword">case</span><span class="token punctuation">;</span>
    
    <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'您输入的月份为 :'</span><span class="token punctuation">,</span> <span class="token keyword">month</span> <span class="token punctuation">,</span> <span class="token string">',该月份为 : '</span> <span class="token punctuation">,</span> result<span class="token punctuation">)</span> <span class="token keyword">as</span> content <span class="token punctuation">;</span>
<span class="token keyword">end</span>$
<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test9<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="5、mysql存储过程中的三种循环"><a href="#5、mysql存储过程中的三种循环" class="headerlink" title="5、mysql存储过程中的三种循环"></a>5、mysql存储过程中的三种循环</h4><h6 id="1、while循环"><a href="#1、while循环" class="headerlink" title="1、while循环"></a>1、while循环</h6><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 如果循环条件为true，则一直执行do后面的sql语句，如果循环条件为false，则结束while循环</span>
<span class="token keyword">while</span> 循环条件 <span class="token keyword">do</span>

	<span class="token keyword">sql</span>语句

<span class="token keyword">end</span> <span class="token keyword">while</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>需求:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">计算从 <span class="token number">1</span>加到n的值<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>sql</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">delimiter</span> $	
<span class="token comment">-- 创建存储过程，使用变量n接收传入的参数</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test10<span class="token punctuation">(</span><span class="token operator">in</span> n <span class="token keyword">int</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
	<span class="token comment">-- 声明变量total保存最后的和值，默认值是0</span>
    <span class="token keyword">declare</span> total <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token comment">-- 声明变量num初始化值是1作为循环的初始化</span>
    <span class="token keyword">declare</span> num <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token comment">-- num&lt;=n 表示循环条件，如果为true，满足循环条件执行do后面的sql语句即循环体</span>
    <span class="token keyword">while</span> num<span class="token operator">&lt;=</span>n <span class="token keyword">do</span>
    	<span class="token comment">-- 每次循环设置total的值为total + num</span>
      	<span class="token keyword">set</span> total <span class="token operator">=</span> total <span class="token operator">+</span> num<span class="token punctuation">;</span>
      	<span class="token comment">-- 每次循环让num进行+1</span>
    	<span class="token keyword">set</span> num <span class="token operator">=</span> num <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">end</span> <span class="token keyword">while</span><span class="token punctuation">;</span>
    <span class="token comment">-- 查看和值total</span>
    <span class="token keyword">select</span> total<span class="token punctuation">;</span>
<span class="token keyword">end</span>$

<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test10<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h6 id="2、repeat结构"><a href="#2、repeat结构" class="headerlink" title="2、repeat结构"></a>2、repeat结构</h6><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 如果不满足until后面的循环条件则执行循环体代码，直到满足循环条件就结束循环体代码</span>
<span class="token keyword">repeat</span>
	<span class="token comment">-- 循环体</span>
    <span class="token keyword">sql</span>语句
    until  循环条件 <span class="token comment">-- 注意：循环条件后面不能加分号，不满足语法规则</span>
<span class="token keyword">end</span> <span class="token keyword">repeat</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>需求:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">计算从 <span class="token number">1</span>加到n的值<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>sql</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">delimiter</span> $
<span class="token comment">-- 创建存储过程</span>
<span class="token comment">-- 使用参数n接收调用存储过程传入的数据</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test11<span class="token punctuation">(</span><span class="token operator">in</span> n <span class="token keyword">int</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
	<span class="token comment">-- 声明变量total保存和值，初始化值是0</span>
    <span class="token keyword">declare</span> total <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token comment">-- 使用repeat循环</span>
    <span class="token keyword">repeat</span>
    	<span class="token comment">-- 每次循环设置total等于total + n 就是求n+(n-1)....+1</span>
      	<span class="token keyword">set</span> total <span class="token operator">=</span> total <span class="token operator">+</span> n<span class="token punctuation">;</span>
      	<span class="token comment">-- 每次循环将n进行减1</span>
      	<span class="token keyword">set</span> n <span class="token operator">=</span> n <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>
      	<span class="token comment">-- 当n等于0时停止repeat循环，这里不能加分号否则报错</span>
    	until n<span class="token operator">=</span><span class="token number">0</span> 
    <span class="token keyword">end</span> <span class="token keyword">repeat</span><span class="token punctuation">;</span>
    <span class="token comment">-- 查看总和值total</span>
    <span class="token keyword">select</span> total <span class="token punctuation">;</span>
<span class="token keyword">end</span>$

<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test11<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h6 id="3、loop-leave语句"><a href="#3、loop-leave语句" class="headerlink" title="3、loop leave语句"></a>3、loop leave语句</h6><p>loop 实现简单的循环，退出循环的条件需要使用其他的语句定义，通常可以使用 leave 语句实现</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment"># 死循环，需要用leave才能跳出</span>

循环标记:<span class="token keyword">loop</span>
    <span class="token comment">-- 循环体</span>
    <span class="token keyword">sql</span>语句
    <span class="token keyword">if</span> 条件 <span class="token keyword">then</span>
    	<span class="token keyword">leave</span> 循环标记<span class="token punctuation">;</span>
<span class="token keyword">end</span> <span class="token keyword">loop</span> 循环标记<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>需求: 使用loop和leave实现数字累加</p>
<p>sql:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">delimiter</span> $
<span class="token comment">-- 创建存储过程</span>
<span class="token comment">-- 使用参数n接收调用存储过程传入的数据</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test12<span class="token punctuation">(</span><span class="token operator">in</span> n <span class="token keyword">int</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
	<span class="token comment">-- 声明变量total保存和值，初始化值是0</span>
    <span class="token keyword">declare</span> total <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token comment">-- 使用loop循环,c表示循环别名</span>
    c:<span class="token keyword">loop</span>
    	<span class="token comment">-- 每次循环设置total等于total + n 就是求n+(n-1)....+1</span>
      	<span class="token keyword">set</span> total <span class="token operator">=</span> total <span class="token operator">+</span> n<span class="token punctuation">;</span>
      	<span class="token comment">-- 每次循环将n进行减1</span>
      	<span class="token keyword">set</span> n <span class="token operator">=</span> n <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>
      	<span class="token comment">-- 判断n是否小于等于0，如果是结束loop循环</span>
      	<span class="token keyword">if</span> n<span class="token operator">&lt;=</span> <span class="token number">0</span> <span class="token keyword">then</span>
      		<span class="token comment">-- 说明n小于等于0了，使用leave结束loop循环</span>
      		<span class="token keyword">leave</span> c<span class="token punctuation">;</span>
      	<span class="token keyword">end</span> <span class="token keyword">if</span><span class="token punctuation">;</span>
    <span class="token comment">-- 结束loop循环后面加一个loop循环的别名</span>
    <span class="token keyword">end</span> <span class="token keyword">loop</span> c<span class="token punctuation">;</span>
    <span class="token comment">-- 查看总和值total</span>
    <span class="token keyword">select</span> total <span class="token punctuation">;</span>
<span class="token keyword">end</span>$

<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test12<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="5、游标-光标-了解"><a href="#5、游标-光标-了解" class="headerlink" title="5、游标/光标(了解)"></a>5、游标/光标(了解)</h3><blockquote>
<p>游标是用来存储<strong>查询结果集</strong>的 , 在存储过程和函数中可以使用光标对结果集进行循环的处理。光标的使用包括光标的declare(声明)、open(打开)、fetch(获取游标中的数据)和 close(关闭)</p>
</blockquote>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">declare</span> 游标名 <span class="token keyword">cursor</span> <span class="token keyword">for</span> 查询数据的结果集的<span class="token keyword">sql</span>语句 <span class="token punctuation">;</span>  <span class="token comment">-- 声明游标，执行完查询的sql语句之后将结果集放到游标中了</span>
<span class="token keyword">open</span> 游标名 <span class="token punctuation">;</span> <span class="token comment">-- 打开游标</span>
<span class="token keyword">fetch</span> 游标名  <span class="token keyword">INTO</span> 变量名<span class="token punctuation">,</span>变量名 <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token punctuation">;</span> <span class="token comment">-- 获取游标中的数据并赋给指定变量，执行一次fetch获取游标中的一行数据，然后游标中的指针就会向下移动一次</span>
<span class="token keyword">close</span> 游标名<span class="token punctuation">;</span> <span class="token comment">-- 关闭游标</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p><b>方式1-实例sql:查询emp中所有的数据存储到游标中，并取出游标中的数据</b></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">delimiter</span> $
<span class="token comment">-- 创建存储过程</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test13<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
	<span class="token comment">-- 声明和数据表列对应的列来存储列值</span>
	<span class="token keyword">declare</span> e_id <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">declare</span> e_name <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">50</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">declare</span> e_age <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">declare</span> e_salary <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">-- 创建游标</span>
    <span class="token comment">-- emp_result 表示游标名  cursor for 固定的关键字</span>
    <span class="token comment">-- 整体表示将从emp表中查询所有的数据存储到游标emp_result中</span>
    <span class="token keyword">declare</span> emp_result <span class="token keyword">cursor</span> <span class="token keyword">for</span> <span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> emp<span class="token punctuation">;</span>
  
    <span class="token keyword">open</span> emp_result<span class="token punctuation">;</span> <span class="token comment">-- 打开游标</span>
    <span class="token comment">-- 取出游标中的第一行数据放到对应的变量中</span>
    <span class="token keyword">fetch</span> emp_result <span class="token keyword">into</span> e_id<span class="token punctuation">,</span>e_name<span class="token punctuation">,</span>e_age<span class="token punctuation">,</span>e_salary<span class="token punctuation">;</span>
    <span class="token comment">-- 查询变量的结果</span>
     <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'id='</span><span class="token punctuation">,</span>e_id <span class="token punctuation">,</span> <span class="token string">', name='</span><span class="token punctuation">,</span>e_name<span class="token punctuation">,</span> <span class="token string">', age='</span><span class="token punctuation">,</span> e_age<span class="token punctuation">,</span> <span class="token string">', 薪资为:
    '</span><span class="token punctuation">,</span>e_salary<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">--  取出游标中的第2行数据放到对应的变量中</span>
    <span class="token keyword">fetch</span> emp_result <span class="token keyword">into</span> e_id<span class="token punctuation">,</span>e_name<span class="token punctuation">,</span>e_age<span class="token punctuation">,</span>e_salary<span class="token punctuation">;</span>
     <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'id='</span><span class="token punctuation">,</span>e_id <span class="token punctuation">,</span> <span class="token string">', name='</span><span class="token punctuation">,</span>e_name<span class="token punctuation">,</span> <span class="token string">', age='</span><span class="token punctuation">,</span> e_age<span class="token punctuation">,</span> <span class="token string">', 薪资为:
    '</span><span class="token punctuation">,</span>e_salary<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">-- 取出游标中的第3行数据放到对应的变量中</span>
    <span class="token keyword">fetch</span> emp_result <span class="token keyword">into</span> e_id<span class="token punctuation">,</span>e_name<span class="token punctuation">,</span>e_age<span class="token punctuation">,</span>e_salary<span class="token punctuation">;</span>
     <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'id='</span><span class="token punctuation">,</span>e_id <span class="token punctuation">,</span> <span class="token string">', name='</span><span class="token punctuation">,</span>e_name<span class="token punctuation">,</span> <span class="token string">', age='</span><span class="token punctuation">,</span> e_age<span class="token punctuation">,</span> <span class="token string">', 薪资为:
    '</span><span class="token punctuation">,</span>e_salary<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">-- 取出游标中的第4行数据放到对应的变量中</span>
    <span class="token keyword">fetch</span> emp_result <span class="token keyword">into</span> e_id<span class="token punctuation">,</span>e_name<span class="token punctuation">,</span>e_age<span class="token punctuation">,</span>e_salary<span class="token punctuation">;</span>
     <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'id='</span><span class="token punctuation">,</span>e_id <span class="token punctuation">,</span> <span class="token string">', name='</span><span class="token punctuation">,</span>e_name<span class="token punctuation">,</span> <span class="token string">', age='</span><span class="token punctuation">,</span> e_age<span class="token punctuation">,</span> <span class="token string">', 薪资为:
    '</span><span class="token punctuation">,</span>e_salary<span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">close</span> emp_result<span class="token punctuation">;</span> <span class="token comment">-- 关闭游标</span>
<span class="token keyword">end</span>$

<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test13<span class="token punctuation">(</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>方式2-实例sql:</strong></p>
<p>说明：使用循环实现上述过程，但是循环需要结束条件，那么我们在这里怎样书写结束条件呢？</p>
<p>有两种方式：</p>
<p>​    1）查询数据表的所有数据 select count(*)…..将行记录数赋值给变量num,每次循环num都减1，当变量变为0停止循环。</p>
<p>​    2）我们希望当游标的指针移动到最后找不到数据就不找了，对于这种情况mysql提供一种思想就是句柄(出错处理器)，当找不到使用句柄(出错处理器)方式可以实现，<strong>要求声明句柄(出错处理器)和声明游标必须放在一起，并且声明句柄(出错处理器)放在声明游标下面</strong>：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建游标</span>
<span class="token keyword">declare</span> emp_result <span class="token keyword">cursor</span> <span class="token keyword">for</span> <span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> emp<span class="token punctuation">;</span>
<span class="token comment">-- 声明句柄</span>
<span class="token comment">-- declare 表示声明  exit 退出 handler 处理器 set 变量 = 初始化值 设置值</span>
<span class="token keyword">declare</span> <span class="token keyword">exit</span> <span class="token keyword">handler</span> <span class="token keyword">for</span> <span class="token operator">not</span> found <span class="token keyword">set</span> 变量 <span class="token operator">=</span> 初始化值<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>sql语句演示：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">delimiter</span> $
<span class="token comment">-- 创建存储过程</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> pro_test14<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
	<span class="token comment">-- 声明和数据表列对应的列来存储列值</span>
	<span class="token keyword">declare</span> e_id <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">declare</span> e_name <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">50</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">declare</span> e_age <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">declare</span> e_salary <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">-- 声明变量has_data作为游标中的指针是否还可以找到数据，默认值是1表示有数据，0表示没有数据</span>
    <span class="token keyword">declare</span> has_data <span class="token keyword">int</span> <span class="token keyword">default</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token comment">-- 创建游标</span>
    <span class="token comment">-- emp_result 表示游标名  cursor for 固定的关键字</span>
    <span class="token comment">-- 整体表示将从emp表中查询所有的数据存储到游标emp_result中</span>
    <span class="token keyword">declare</span> emp_result <span class="token keyword">cursor</span> <span class="token keyword">for</span> <span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> emp<span class="token punctuation">;</span>
  	<span class="token keyword">declare</span> <span class="token keyword">exit</span> <span class="token keyword">handler</span> <span class="token keyword">for</span> <span class="token operator">not</span> found <span class="token keyword">set</span> has_data <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">open</span> emp_result<span class="token punctuation">;</span> <span class="token comment">-- 打开游标</span>
   
    <span class="token comment">-- 循环</span>
    <span class="token keyword">repeat</span>
     <span class="token comment">-- 取出游标中的第一行数据放到对应的变量中</span>
    <span class="token keyword">fetch</span> emp_result <span class="token keyword">into</span> e_id<span class="token punctuation">,</span>e_name<span class="token punctuation">,</span>e_age<span class="token punctuation">,</span>e_salary<span class="token punctuation">;</span>
     <span class="token comment">-- 查询变量的结果</span>
     <span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'id='</span><span class="token punctuation">,</span>e_id <span class="token punctuation">,</span> <span class="token string">', name='</span><span class="token punctuation">,</span>e_name<span class="token punctuation">,</span> <span class="token string">', age='</span><span class="token punctuation">,</span> e_age<span class="token punctuation">,</span> <span class="token string">', 薪资为:
    '</span><span class="token punctuation">,</span>e_salary<span class="token punctuation">)</span><span class="token punctuation">;</span>
    until has_data <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">end</span> <span class="token keyword">repeat</span><span class="token punctuation">;</span>
    <span class="token keyword">close</span> emp_result<span class="token punctuation">;</span> <span class="token comment">-- 关闭游标</span>
<span class="token keyword">end</span>$

<span class="token comment">-- 调用存储过程</span>
<span class="token keyword">call</span> pro_test13<span class="token punctuation">(</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h2 id="2、存储函数"><a href="#2、存储函数" class="headerlink" title="2、存储函数"></a>2、存储函数</h2><p>函数 ： 是一个有返回值的过程 ；<br>过程 ： 是一个没有返回值的函数 ；</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建存储函数</span>
<span class="token keyword">delimiter</span> $
<span class="token keyword">create</span> <span class="token keyword">function</span> 存储函数名<span class="token punctuation">(</span>参数名 参数类型<span class="token punctuation">)</span>
<span class="token keyword">returns</span> 返回值的数据类型
<span class="token keyword">begin</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
  <span class="token keyword">return</span> 值<span class="token punctuation">;</span>
<span class="token keyword">end</span> $

<span class="token comment">-- 调用存储函数</span>
<span class="token keyword">select</span> 存储函数名<span class="token punctuation">(</span>实参<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>需求: 定义一个存储函数,在city表中根据传入的国家id,计算满足条件的总记录数</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">delimiter</span> $
<span class="token comment">-- 创建存储函数</span>
<span class="token keyword">create</span> <span class="token keyword">function</span> fn1<span class="token punctuation">(</span>countryId <span class="token keyword">int</span><span class="token punctuation">)</span>
<span class="token keyword">returns</span> <span class="token keyword">int</span>
<span class="token keyword">begin</span>
	<span class="token keyword">declare</span> cnum <span class="token keyword">int</span> <span class="token punctuation">;</span>
	<span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token operator">*</span><span class="token punctuation">)</span> <span class="token keyword">into</span> cnum <span class="token keyword">from</span> city <span class="token keyword">where</span> country_id <span class="token operator">=</span> countryId<span class="token punctuation">;</span>
	<span class="token keyword">return</span> cnum<span class="token punctuation">;</span>
<span class="token keyword">end</span>$

<span class="token comment">-- 调用存储函数</span>
<span class="token keyword">select</span> fn1<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p><strong>mysql的设置默认是不允许创建函数。</strong></p>
<p>通过如下命令可以查看函数开启状态：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">show</span> variables <span class="token operator">like</span> <span class="token string">'%func%'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><img src="https://i.loli.net/2021/09/02/izS5EAhPdqM7tyQ.png" alt="image-20200731101140383"></p>
<ul>
<li><p>解决办法1:开启函数功能即可。</p>
<p>在MySQL中创建函数时出现这种错误的解决方法：</p>
</li>
</ul>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">set</span> <span class="token keyword">global</span> log_bin_trust_function_creators<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>不过这种做法重启mysql服务， 就失效了，又会变为off.</p>
<ul>
<li><p>解决办法2：</p>
<p>在my.ini里面设置</p>
</li>
</ul>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">log<span class="token operator">-</span>bin<span class="token operator">-</span>trust<span class="token operator">-</span><span class="token keyword">function</span><span class="token operator">-</span>creators<span class="token operator">=</span><span class="token number">1</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>不过这个需要重启服务.</p>
<h2 id="3、mysql体系"><a href="#3、mysql体系" class="headerlink" title="3、mysql体系"></a>3、mysql体系</h2><p><img src="https://i.loli.net/2021/09/02/mdj1RDnciuqvZCE.png" alt="image-20210902110712861"></p>
<h2 id="整个-MySQL-Server由以下组成"><a href="#整个-MySQL-Server由以下组成" class="headerlink" title="整个 MySQL Server由以下组成"></a>整个 MySQL Server由以下组成</h2><ul>
<li>Connection Pool :  连接池组件。<strong>连接池</strong>： 管理、缓冲用户的连接，线程处理等需要缓存的需求。</li>
<li>Management Services &amp; Utilities :  管理服务和工具组件。系统管理和控制工具，例如备份恢复、Mysql复制、集群等 </li>
<li>SQL Interface : SQL 接口组件。接受用户的SQL命令，并且返回用户需要查询的结果。</li>
<li>Parser :  查询分析器组件。SQL命令传递到解析器的时候会被解析器验证和解析(权限、语法结构) </li>
<li>Optimizer :  优化器组件。SQL语句在查询之前会使用查询优化器对查询进行优化</li>
<li>Caches &amp; Buffers :  缓冲池组件。如果查询缓存有命中的查询结果，查询语句就可以直接去查询缓存中取数据</li>
<li>Pluggable Storage Engines :  存储引擎。存储引擎说白了就是如何管理操作数据（存储数据、如何更新、查询数据等）的一种方法。因为在关系数据库中数据的存储是以表的形式存储的，所以存储引擎也可以称为表类型（即存储和操作此表的类型）</li>
<li>File System :  文件系统。存储的文件系统不仅包含数据，还包括索引、错误日志和慢查询日志等</li>
</ul>
<p><strong>总结：</strong></p>
<pre class="line-numbers language-markdown" data-language="markdown"><code class="language-markdown">1.客户端连接器：
	可以使用各种不同的语言与数据库服务进行交互；
2.mysql服务
	核心组件：
		【1】连接池：用户认证（初步校验，校验用户名称或者密码是否正确）、线程复用、限制客户端的连接数，起到安全的作用等；
		【2】SQL接口：专门接收客户端发送过来的sql语句（接收sql的门户）
		【3】Parser:解析器，核心对sql语法进行解析，解析当前发送sql的用户是否对这个sql有执行的权限（access denied）；
		【4】Optimizer:查询优化器，决定你的sql是否走索引，以及是否走什么索引，生成sql的执行计划；
				select * from t where name like 'zhang%' and age &gt; 38;
                前提：name 和age 都创建了索引，应该走哪个索引呢？
                    如果走name索引，查询出10w,如果走age，那么查询出1w;[索引查询小结果驱动]
                数据库如何知道哪个索引查询结果多或者少呢？
                    采样算法：从叶子节点随机采样几块，然后做大致判断；
        【5】存储引擎：mysql与其他数据库不同，它才用插拔式的设计思想，将对数据的处理层抽取，叫做存储引擎； 说白了，存储引擎是存储数据，构建索引的技术，sql的增删改查操作都是由存储引擎层完成的；
        【6】文件系统：存储引擎底层调用系统的文件系统完成数据的操作；         
3.其他：
	管理服务和工具：
		数据库备份与还原；
		管理mysql集群等；
	缓存组件：
    	作用：接口客户端的sql后，对sql进行hash运算得到换一个key，然后根据这个key从缓存中获取缓存数据，如果缓存的数据存在，直接响应客户端；
    	弊端：如果数据库一旦发生增删改操作，那么缓存数据清空；缓存维护成本很高，但是清理成本很低；
    	5.6 版本有缓存组件，但是到了8版本以上，这个模块剔除了；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h2 id="4、存储引擎"><a href="#4、存储引擎" class="headerlink" title="4、存储引擎"></a>4、存储引擎</h2><blockquote>
<p>存储引擎是基于表的，而不是基于库的.</p>
<p>MySQL5.0支持的存储引擎包含 ： InnoDB 、MyISAM 、BDB、MEMORY、MERGE、EXAMPLE、NDB Cluster、ARCHIVE、CSV、BLACKHOLE、FEDERATED等，其中InnoDB和BDB提供事务安全表，其他存储引擎是非事务安全表。</p>
</blockquote>
<ul>
<li>可以通过指定 show engines ， 来查询当前数据库支持的存储引擎 </li>
<li>MySQL5.5之前的默认存储引擎是MyISAM，5.5之后就改为了InnoDB。</li>
</ul>
<p><strong>查看Mysql数据库默认的存储引擎 ， 指令</strong></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">show</span> variables <span class="token operator">like</span> <span class="token string">'%storage_engine%'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>





<h3 id="1、存储引擎特性"><a href="#1、存储引擎特性" class="headerlink" title="1、存储引擎特性"></a>1、存储引擎特性</h3><p>下面重点介绍几种常用的存储引擎， 并对比各个存储引擎之间的区别， 如下表所示 ：</p>
<table>
<thead>
<tr>
<th>特点</th>
<th>InnoDB</th>
<th>MyISAM</th>
<th>MEMORY</th>
<th>MERGE</th>
<th>NDB</th>
</tr>
</thead>
<tbody><tr>
<td>存储限制</td>
<td>64TB</td>
<td>有</td>
<td>有</td>
<td>没有</td>
<td>有</td>
</tr>
<tr>
<td>事务安全</td>
<td><span style="background-color:yellow;">支持</span></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>锁机制</td>
<td><span style="background-color:yellow;">行锁(适合高并发)</span></td>
<td><span style="background-color:yellow;">表锁</span></td>
<td>表锁</td>
<td>表锁</td>
<td>行锁</td>
</tr>
<tr>
<td>B树索引</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>哈希索引</td>
<td></td>
<td></td>
<td>支持</td>
<td></td>
<td></td>
</tr>
<tr>
<td>全文索引</td>
<td>支持(5.6版本后)</td>
<td>支持</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>集群索引</td>
<td>支持</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>数据索引</td>
<td>支持</td>
<td></td>
<td>支持</td>
<td></td>
<td>支持</td>
</tr>
<tr>
<td>索引缓存</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>数据可压缩</td>
<td></td>
<td>支持</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>空间使用</td>
<td>高</td>
<td>低</td>
<td>N/A</td>
<td>低</td>
<td>低</td>
</tr>
<tr>
<td>内存使用</td>
<td>高</td>
<td>低</td>
<td>中等</td>
<td>低</td>
<td>高</td>
</tr>
<tr>
<td>批量插入速度</td>
<td>低</td>
<td>高</td>
<td>高</td>
<td>高</td>
<td>高</td>
</tr>
<tr>
<td>支持外键</td>
<td><span style="background-color:yellow;">支持</span></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<p>下面我们将重点介绍最长使用的两种存储引擎： InnoDB、MyISAM ， 另外几种 了解即可。</p>
<h4 id="1、InnoDB（聚集索引）"><a href="#1、InnoDB（聚集索引）" class="headerlink" title="1、InnoDB（聚集索引）"></a>1、InnoDB（聚集索引）</h4><pre class="line-numbers language-markdown" data-language="markdown"><code class="language-markdown">支持外键
支持事务
支持行锁(支持表锁)
支持数据崩溃后的自动恢复<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建 innodb存储引擎表</span>
<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> tab_innodb<span class="token punctuation">(</span>
 id <span class="token keyword">INT</span><span class="token punctuation">,</span>
 name <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token keyword">ENGINE</span> <span class="token operator">=</span> <span class="token keyword">INNODB</span><span class="token punctuation">;</span> <span class="token comment">-- 这里不指定ENGINE = INNODB默认也是INNODB</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上述创建好数据表之后，在对应的mysql安装目录的数据库下面会创建如下两个文件：</p>
<p><img src="https://i.loli.net/2021/09/02/DwWAHceUtmdNCqB.png" alt="1588659606099"> </p>
<p>说明：</p>
<p>​    1.InnoDB存储引擎是将数据和索引都存储在一个文件中即.ibd中了。所以InnoDB存储引擎也称为聚集索引，因为将数据和索引放在一个文件中了。</p>
<p>​    2.InnoDB存储引擎是Mysql的默认存储引擎。InnoDB存储引擎提供了具有提交、回滚、恢复能力的事务安全。但是对比MyISAM的存储引擎，InnoDB写的处理效率差一些。</p>
<h4 id="2、MyISAM（非聚集索引）"><a href="#2、MyISAM（非聚集索引）" class="headerlink" title="2、MyISAM（非聚集索引）"></a>2、MyISAM（非聚集索引）</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">支持表锁<span class="token punctuation">(</span>不支持行锁<span class="token punctuation">)</span>
不支持事务
不支持外键
不支持数据崩溃后自动恢复<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建 myisam存储引擎表</span>
<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> tab_myisam<span class="token punctuation">(</span>
 id <span class="token keyword">INT</span><span class="token punctuation">,</span>
 name <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token keyword">ENGINE</span><span class="token operator">=</span>MYISAM<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><img src="https://i.loli.net/2021/09/02/6bqEpOJB7NZStFo.png" alt="1588659151895"> </p>
<p>说明：</p>
<p>​    1.MyISAM存储引擎将数据和索引存入两个不同的文件。</p>
<p>​    2.MyISAM 不支持事务、也不支持外键，其优势是访问的速度快，对事务的完整性没有要求可以使用这个引擎来创建表 。</p>
<h4 id="3-存储引擎选择"><a href="#3-存储引擎选择" class="headerlink" title="3 存储引擎选择"></a>3 存储引擎选择</h4><p>在选择存储引擎时，应该根据应用系统的特点选择合适的存储引擎。对于复杂的应用系统，还可以根据实际情况选择多种存储引擎进行组合。以下是几种常用的存储引擎的使用环境。</p>
<ul>
<li>InnoDB :  是Mysql的默认存储引擎，用于事务处理应用程序，支持外键。如果应用对事务的完整性有比较高的要求，在并发条件下要求数据的一致性，数据操作除了插入和查询以外，还包含很多的更新、删除操作，那么InnoDB存储引擎是比较合适的选择。InnoDB存储引擎除了有效的降低由于删除和更新导致的锁定， 还可以确保事务的完整提交和回滚，对于类似于计费系统或者财务系统等对数据准确性要求比较高的系统，InnoDB是最合适的选择。</li>
<li>MyISAM  ： 如果应用是以读操作和插入操作为主，只有很少的更新和删除操作，并且对事务的完整性、并发性要求不是很高，那么选择这个存储引擎是非常合适的。</li>
</ul>
<p><strong>总结：</strong></p>
<p>聚集索引</p>
<pre class="line-numbers language-none"><code class="language-none">表中的索引和数据存储到一块	<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><img src="https://i.loli.net/2021/09/02/YADVMLyglaKWm4X.png" alt="image-20210902140515864"></p>
<p>非聚集索引</p>
<pre class="line-numbers language-none"><code class="language-none">表中的索引和数据分文件独立存储<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><img src="https://i.loli.net/2021/09/02/2AZlYRE8exOVWBM.png" alt="image-20210902140559193"></p>
<h2 id="5、锁"><a href="#5、锁" class="headerlink" title="5、锁"></a>5、锁</h2><h3 id="1、-锁分类"><a href="#1、-锁分类" class="headerlink" title="1、 锁分类"></a>1、 锁分类</h3><p>从对数据操作的粒度分 ：</p>
<ul>
<li><p> 表锁：操作时，会锁定整个表。</p>
</li>
<li><p> 行锁：操作时，会锁定当前操作行。</p>
</li>
</ul>
<p>从对数据操作的类型分：</p>
<ul>
<li><p>读锁（共享锁）：针对同一份数据，多个读操作可以同时进行而不会互相影响。</p>
</li>
<li><p>写锁（排它锁）：当前操作没有完成之前，它会阻断其他线程的写锁和读锁。</p>
</li>
</ul>
<h3 id="2、Mysql锁"><a href="#2、Mysql锁" class="headerlink" title="2、Mysql锁"></a>2、Mysql锁</h3><p>MySQL的锁机制比较简单，其最显著的特点是不同的存储引擎支持不同的锁机制。下表中罗列出了各存储引擎对锁的支持情况：</p>
<table>
<thead>
<tr>
<th>存储引擎</th>
<th>表级锁</th>
<th>行级锁</th>
<th>页面锁(了解)</th>
</tr>
</thead>
<tbody><tr>
<td>MyISAM</td>
<td>支持</td>
<td>不支持</td>
<td>不支持</td>
</tr>
<tr>
<td>InnoDB</td>
<td>支持</td>
<td>支持(默认)</td>
<td>不支持</td>
</tr>
</tbody></table>
<h3 id="3、MyISAM表锁"><a href="#3、MyISAM表锁" class="headerlink" title="3、MyISAM表锁"></a>3、MyISAM表锁</h3><h4 id="如何加表锁"><a href="#如何加表锁" class="headerlink" title="如何加表锁"></a>如何加表锁</h4><p>MyISAM 在执行查询语句（SELECT）前，会自动给涉及的所有表加读锁，在执行更新操作（UPDATE、DELETE、INSERT 等）前，会自动给涉及的表加写锁，这个过程并不需要用户干预，因此，用户一般不需要直接用</p>
<p> LOCK    TABLE 命令给 MyISAM 表显式加锁。如果显示加表锁，那么就不会自动加表锁。</p>
<div style="background-color:orange;">加表锁语法: </div>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">加读锁 : <span class="token keyword">lock</span> <span class="token keyword">table</span> 表名 <span class="token keyword">read</span><span class="token punctuation">;</span>
加写锁 : <span class="token keyword">lock</span> <span class="token keyword">table</span> 表名 <span class="token keyword">write</span>；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h4 id="1、MYISAM读锁"><a href="#1、MYISAM读锁" class="headerlink" title="1、MYISAM读锁"></a>1、MYISAM读锁</h4><pre class="line-numbers language-none"><code class="language-none">读锁是共享锁，允许其他会话读，阻塞其他会话写。
当我这个会话拿到读锁时，我可以读但不能写，其他会话也是写操作会阻塞，读操作不会阻塞。
当你要查询其他表时，需要将当前的锁释放，其他表才能得到锁。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h4 id="2、MYISAM写锁"><a href="#2、MYISAM写锁" class="headerlink" title="2、MYISAM写锁"></a>2、MYISAM写锁</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">写锁是排他锁，不允许其他会话读写，自己可以读写。
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>




<pre class="line-numbers language-none"><code class="language-none">1） 对MyISAM 表的读操作，不会阻塞其他用户对同一表的读请求，但会阻塞对同一表的写请求；

2） 对MyISAM 表的写操作，则会阻塞其他用户对同一表的读和写操作；

简而言之，就是读锁会阻塞写，但是不会阻塞读。而写锁，则既会阻塞读，又会阻塞写。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="4、innodb行锁"><a href="#4、innodb行锁" class="headerlink" title="4、innodb行锁"></a>4、innodb行锁</h3><h4 id="行锁介绍"><a href="#行锁介绍" class="headerlink" title="行锁介绍"></a>行锁介绍</h4><pre class="line-numbers language-markdown" data-language="markdown"><code class="language-markdown">行锁特点 ：
        ①InnoDB 存储引擎默认采用行级锁；
        ②因为行锁粒度小，所以性能开销相对较大，加锁相对较慢；
        ③行锁可能会出现死锁问题；
        ④行锁的锁定粒度较小，发生锁冲突的概率最低,所以相对支持较高的写并发；
        ⑤Innodb支持事务特性，底层行级锁也有参与(通过索引更新一行时，加行锁)；

InnoDB 与 MyISAM 的最大不同有两点：一是InnoDB 支持事务；二是 InnoDB 采用了行级锁。行级锁也是和事务有关的。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="InnoDB的行锁模式"><a href="#InnoDB的行锁模式" class="headerlink" title="InnoDB的行锁模式"></a>InnoDB的行锁模式</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">InnoDB</span> 实现了以下两种类型的行锁:
共享锁（S <span class="token operator">-</span><span class="token keyword">share</span>）：又称为读锁，简称S锁，共享锁就是多个事务对于同一数据可以共享一把锁，都能访问到数据，但是只能读不能修改。
排他锁（X<span class="token operator">-</span>exclusion）：又称为写锁，简称X锁，排他锁就是不能与其他锁并存，如一个事务获取了一个数据行的排他锁，其他事务就不能再获取该行的其他锁，但是获取排他锁的当前的事务是可以对数据就行读取和修改。
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>对于UPDATE、DELETE和INSERT语句，InnoDB会自动给涉及数据集加排他锁（X)；</p>
<p>对于普通SELECT语句，InnoDB不会加任何锁；</p>
<p>可以通过以下语句显示给记录集加共享锁或排他锁 。</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">共享锁（ S）: <span class="token keyword">SELECT</span> <span class="token operator">*</span> <span class="token keyword">FROM</span> table_name <span class="token keyword">WHERE</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token keyword">LOCK</span> <span class="token operator">IN</span> <span class="token keyword">SHARE</span> <span class="token keyword">MODE</span>
排他锁（X<span class="token punctuation">)</span> : <span class="token keyword">SELECT</span> <span class="token operator">*</span> <span class="token keyword">FROM</span> table_name <span class="token keyword">WHERE</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token keyword">FOR</span> <span class="token keyword">UPDATE</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<pre class="line-numbers language-markdown" data-language="markdown"><code class="language-markdown"> Innodb的行锁依赖于事务；
一个事务获取了行锁后，在这个事务未提交之前，其他事务如果操作的时相同的行，那么需要阻塞等待获取锁的事务提交后释放行锁，才能解除阻塞；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<h4 id="InnoDB-行锁升级表锁"><a href="#InnoDB-行锁升级表锁" class="headerlink" title="InnoDB 行锁升级表锁"></a><strong>InnoDB 行锁升级表锁</strong></h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">原因：索引失效（在更新或者删除等写操作中，如果操作条件不走索引或者索引失效时，会导致写操作全表扫描查找要更改的数据，进而导致表锁


<span class="token number">1</span>）在索引字段下<span class="token operator">*</span><span class="token operator">*</span>使用函数<span class="token operator">*</span><span class="token operator">*</span>，导致索引失效；
<span class="token number">2</span>）在索引字段下进行<span class="token operator">*</span><span class="token operator">*</span>类型转换<span class="token operator">*</span><span class="token operator">*</span>；
<span class="token number">3</span>）在索引字段下使用<span class="token operator">*</span><span class="token operator">*</span>数学运算<span class="token operator">*</span><span class="token operator">*</span>；
<span class="token number">4</span>）在索引字段频繁进行写操作；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="间隙锁"><a href="#间隙锁" class="headerlink" title="间隙锁"></a>间隙锁</h4><p>当我们用范围条件，而不是使用相等条件检索数据，并请求共享或排他锁时，InnoDB会给符合条件的已有数据进行加锁； 对于键值在条件范围内但并不存在的记录，叫做 “间隙（GAP）” ， InnoDB也会对这个 “间隙” 加锁，这种锁机制就是所谓的 间隙锁（Next-Key锁） 。</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">数据库存在数据的主键是：
<span class="token number">1</span>
<span class="token number">3</span>
<span class="token number">4</span>
<span class="token number">6</span>
<span class="token number">9</span>
如果条件是：id <span class="token operator">&lt;</span> <span class="token number">10</span>
这里id缺少的是<span class="token number">2</span> <span class="token number">5</span> <span class="token number">7</span> <span class="token number">8</span> 。他们就称为间隙，<span class="token keyword">InnoDB</span>也会对这些间隙进行加锁，这种锁机制就是所谓的 间隙锁<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">一个事务中进行范围的写操作<span class="token punctuation">,</span>那么其他事务就不能再这个范围内写数据<span class="token punctuation">;</span>

作用：用于避免在范围查询时的幻读现象，不能完全避免幻读。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>



<h4 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h4><pre class="line-numbers language-none"><code class="language-none">innodb行锁的特点？
	Innodb行锁是基于事务的,同时行锁对其它同一行的写操作阻塞;

innodb表锁出现的原因？
	1)更新或者删除的条件下的字段没有添加索引;
	2)索引失效导致表锁

索引失效原因有哪些?
	1.字段类型装换
	2.索引字段使用函数
	3.索引字段进行数学运算 
	4.索引字段进行高频的写操作等

间隙锁特点是什么?
	1.一个事务中进行范围的写操作,那么其他事务就不能再这个范围内写数据；
	2.间隙锁在一定程度了避免了幻读的发生<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Long</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://ergou15154.gitee.io/posts/30bd1158.html">https://ergou15154.gitee.io/posts/30bd1158.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Long</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">
                                    <span class="chip bg-color">数据库</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo,twitter,facebook,google,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/null" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/null" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    .v[data-class="v"] .vwrap .vheader .vinput {
      width: 32%;
      border-bottom: 1px dashed #dedede;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
let metaPlaceholder = {"nick":"昵称/QQ号(必填)","mail":"邮箱(必填)","link":"网址(https://)"} ;
//这里要换行
new Valine({
        el: '#vcomments',
        appId: 'Ucrxxxxxxxxxxxxxxxx-xxxxsz',
        appKey: 'zPsLxxxxxxxxxxxxxxerLmd',
        notify: 'true' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'monsterid',
        pageSize: '10',
        lang: 'zh-CN',
        placeholder: '留下你的足迹..',
        meta: ["nick", "mail", "link"],
        recordIP: 'true' === 'true',
        enableQQ: 'monsterid',
        requiredFields: ["d142de78a3402022b268b12dab90d819"],
        master: ["d142de78a3402022b268b12dab90d819"],
        friends: ["cb3e577ff029d6073400d5557effd41f", ""],
        tagMeta: ["博主", "小伙伴", "访客"],
        metaPlaceholder: metaPlaceholder,

    });

    document.body.addEventListener('click', function(e) {
        if (e.target.classList.contains('vsubmit')) {
            const email = document.querySelector('input[type=email]');
            const nick = document.querySelector('input[name=nick]');
            const reg = /^[A-Za-z0-9_-\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if (!email.value || !nick.value || !reg.test(email.value)) {
                const str = `<div class="valert txt-center"><div class="vtext">请填写正确的昵称和邮箱！</div></div>`;
                const vmark = document.querySelector('.vmark');
                vmark.innerHTML = str;
                vmark.style.display = 'block';

                e.stopPropagation();

                setTimeout(function() {
                    vmark.style.display = 'none';
                    vmark.innerHTML = '';
                }, 2500);
            }
        }
        }, true);
</script>



    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/a1e44ab1.html">
                    <div class="card-image">
                        
                        <img src="/medias/banner/8.jpg" class="responsive-img" alt="03 函数-索引-事务-视图+触发器">
                        
                        <span class="card-title">03 函数-索引-事务-视图+触发器</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            函数-索引-事务-视图+触发器
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-15
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-category">
                                    数据库
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">
                        <span class="chip bg-color">数据库</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/bdbcd9c7.html">
                    <div class="card-image">
                        
                        <img src="/medias/banner/13.jpg" class="responsive-img" alt="06Mybatis进阶">
                        
                        <span class="card-title">06Mybatis进阶</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            入参+参数值获取+resultMap简单映射+sql片段+高级映射
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Mybatis/" class="post-category">
                                    Mybatis
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Mybatis/">
                        <span class="chip bg-color">Mybatis</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: Long<br />'
            + '文章作者: Long<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="tencent"
                   type="playlist"
                   id="1776127550"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2021</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Long</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">155.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "10";
                    var startDate = "25";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn/" target="_blank">闽ICP备xxxxxxx号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/vegetable-dog16546/" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1694162702@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1694162702" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1694162702" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



    <a href="6788560391" class="tooltipped" target="_blank" data-tooltip="关注我的微博: 6788560391" data-position="top" data-delay="50">
        <i class="fab fa-weibo"></i>
    </a>





    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.11/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?aaa6c944b0ed07922901d7fc571a171d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

<!-- 深色模式按钮 -->
    <script>
        if (localStorage.getItem('dark') === '1') {
        document.body.classList.add('dark');
        }
        else if (new Date().getHours() >= 22 || new Date().getHours() < 7) {
        document.body.classList.add('dark');
        } 
        else if (matchMedia('(prefers-color-scheme: dark)').matches) {
        document.body.classList.add('dark');
        }
    </script>
    <a onclick="switchNightMode()" id="sma">
        <i class="fas fa-lightbulb" id="nightMode" aria-hidden="true"></i>
    </a>

    <!-- 天气接口控件   -->
    
        <script type="text/javascript">
        WIDGET = {FID: 'zLkJSQpqsh'}
        </script>
    <!-- <script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"></script> -->

    <script type="text/javascript">
      var windowWidth = $(window).width();
      if (windowWidth > 768) {
          document.write('<script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"><\/script>');
      }
    </script>
    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "4xxxxxxxe"
        });
        daovoice('update');
    </script>
    

	
    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
